package com.cloudptt.api.product.update;


import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.content.FileProvider;

import com.cloudptt.api.product.log.Log;

import java.io.File;

public class InstallUtil {
    public static void installApk(Context context, File apkFile) {
        if (!apkFile.exists()) return;
        Log.debug(InstallUtil.class, "installApk apkFile = " + apkFile);
        Uri apkUri = getApkUri(context, apkFile);
        Log.debug(InstallUtil.class, "installApk apkUri = " + apkUri);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Log.debug(InstallUtil.class, "installApk SDK_INT = " + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            handleOreoInstall(context, intent);
        } else {
            context.startActivity(intent);
        }
    }

    private static Uri getApkUri(Context context, File apkFile) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(
                    context,
                    context.getPackageName() + ".fileprovider",
                    apkFile
            );
        } else {
            return Uri.fromFile(apkFile);
        }
    }

    private static void handleOreoInstall(Context context, Intent installIntent) {
        Log.debug(InstallUtil.class, "handleOreoInstall installIntent = " + installIntent);
        if (context.getPackageManager().canRequestPackageInstalls()) {
            context.startActivity(installIntent);
        } else {
            Intent requestIntent = new Intent(
                    Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
                    Uri.parse("package:" + context.getPackageName())
            );
            context.startActivity(requestIntent);
        }
    }
}

